var multiparty = require('multiparty');
var fs = require('fs');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var connection = require("../../app_modules/dbAccess/appConfig.js");
var moment = require('moment');

//id:为objectid
exports.uploadFIle = function (id, inputFile, metadata) {
	var headerString = JSON.stringify(inputFile.headers, null, 2).replace("content-type", "content_type");
	var header = JSON.parse(headerString);
	var mygrid = {};
	mygrid.inputFile = inputFile;
	mygrid.path = inputFile.path;
	mygrid.fileObj = {
		_id: id,
		filename: inputFile.originalFilename,
		mode: 'w',
		chunkSize: inputFile.size,
		content_type: header.content_type,
		root: 'user_files'
	}
	metadata.id=id;
	metadata.fileName=inputFile.originalFilename;
	metadata.fileType=inputFile.originalFilename.split(".")[1];
	metadata.createDate=moment().format('YYYY-MM-DD HH:MM');

	mygrid.fileObj.metadata = metadata;
	exports.createGridfs(mygrid);
}




exports.createGridfs = function (mygrid) {
	var conn = mongoose.createConnection(connection.getConnectionString(""));
	var Grid = require('gridfs-stream');
	conn.once('open', function () {
		var gfs = Grid(conn.db, mongoose.mongo);
		var writestream = gfs.createWriteStream(mygrid.fileObj);
		fs.createReadStream(mygrid.path).pipe(writestream);		
	})
};


exports.getGridfs = function (id, res) {
	var writerStream = fs.createWriteStream('public/files/images/113333322.jpg');
	var conn = mongoose.createConnection(connection.getConnectionString(""));
	var Grid = require('gridfs-stream');
	conn.once('open', function () {
		var gfs = Grid(conn.db, mongoose.mongo);	
		var readstream = gfs.createReadStream({ _id: id, root: 'user_files' });
		readstream.pipe(writerStream);
		//readstream.pipe(res);
		//获取其中的一项的信息
		gfs.findOne({ _id: id, root: 'user_files' }, function (err, file) { console.log(file) });

		res.send("h");
	})
};

exports.removeGridfs = function (id, res) {
	var conn = mongoose.createConnection(connection.getConnectionString(""));
	var Grid = require('gridfs-stream');
	conn.once('open', function () {
		var gfs = Grid(conn.db, mongoose.mongo);
		gfs.remove({ _id: id, root: "user_files" }, function (err) {
			console.log('success');
		});
	})
}

exports.gridfsExist = function (id, res) {
	var conn = mongoose.createConnection(connection.getConnectionString(""));
	var Grid = require('gridfs-stream');
	conn.once('open', function () {
		var gfs = Grid(conn.db, mongoose.mongo);
		gfs.exist({_id: id, root: 'user_files' }, function (err, found) {
			found ? console.log('File exists') : console.log('File does not exist');
		});
	})
}
